import axios from 'axios'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElNotification } from 'element-plus';

// 定义API基础配置
const api = axios.create({
  baseURL: '/api/demo',
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器，添加token
api.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器，处理错误
api.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data
  },
  (error) => {
    const errorMsg = error.response?.data?.message || '请求失败，请稍后再试'
    ElNotification.error({
      title: '错误',
      message: errorMsg
    })
    return Promise.reject(error)
  }
)

export default api